//
//  RelationGroupManagerViewController.m
//  customerRelation
//
//  Created by 陈文斌 on 2019/6/11.
//

#import "FCRelationGroupManagerViewController.h"
#import "CustomerRelationHeader.h"
#import "TopNoticeLabel.h"
#import "FCRelationTypeListModel.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationTypeDefaultCell.h"
#import "FCAddRelationGroupViewController.h"
#import "FCWebViewController.h"
#import "UIViewController+returnBlock.h"

@interface FCRelationGroupManagerViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<FCRelationTypeModel *> *showData;
@property (nonatomic, strong) NSMutableArray<FCRelationTypeModel *> *newShowData;

@end

@implementation FCRelationGroupManagerViewController
- (NSMutableArray<FCRelationTypeModel *> *)newShowData{
    if (!_newShowData) {
        _newShowData = [NSMutableArray array];
    }
    return _newShowData;
}
- (NSMutableArray *)showData{
    if (!_showData) {
        _showData = [NSMutableArray array];

    }
    return _showData;
}

// 创建导航按钮
- (UIBarButtonItem *)itemWithColor:(UIColor *)color highColor:(UIColor *)highColor target:(id)target action:(SEL)action title:(NSString *)title{
    UIView *containerView = [UIView new];
    containerView.frame = (CGRect){.size = CGSizeMake(80, 28)};
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = containerView.bounds;
    [button.titleLabel setFont:font14];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitleColor:highColor forState:UIControlStateHighlighted];
    //    [button sizeToFit];
    //    button.contentEdgeInsets = UIEdgeInsetsMake(4, 8, 6, 7);
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundColor:FCWhiteColor];
    //    button.layer.cornerRadius = 4;
    return  [[UIBarButtonItem alloc] initWithCustomView:button];
}

// 初始化UI
- (void)setupUI{
    self.title = customerRelationLocaChanged(@"分组管理", @"分组管理");
    self.view.backgroundColor = FCBackColor;
    
    // 导航栏添加上下游按钮
    UIBarButtonItem *addBarBut = [self itemWithColor:FCBlueTxtColor highColor:FCBlueTxtColor target:self action:@selector(goAuthorizationNote) title:customerRelationLocaChanged(@"授权说明", @"授权说明")];
    self.navigationItem.rightBarButtonItems = @[addBarBut];
    
    TopNoticeLabel *topNoticeLabel = [[TopNoticeLabel alloc] init];
    topNoticeLabel.noticeTxt = customerRelationLocaChanged(@"拖动分组可以调整关系类型排序，分组负责人可以管理该分组的上下游关", @"拖动分组可以调整关系类型排序，分组负责人可以管理该分组的上下游关");
    topNoticeLabel.noticeLabel.font = font13;
    // 计算高度
    CGSize maximumLabelSize = CGSizeMake(WJCScreenW - (16 * 2 + 20 + 10), CGFLOAT_MAX);// 16:内边距;20:关闭按钮宽度;10:内边距
    CGSize expectSize = [topNoticeLabel.noticeLabel sizeThatFits:maximumLabelSize];
    topNoticeLabel.frame = CGRectMake(0, 0, WJCScreenW, expectSize.height + 20);
    [self.view addSubview:topNoticeLabel];
    
    UIView *bottomView = [UIView new];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.bottom.mas_equalTo(0);
        make.height.mas_equalTo(80 + FCTabbarSafeBottomMargin);
    }];
    bottomView.backgroundColor = FCWhiteColor;
    bottomView.layer.shadowColor = WJCColor(239, 241, 246).CGColor;
    bottomView.layer.shadowOffset = CGSizeMake(0,-4);
    bottomView.layer.shadowOpacity = 1;
    bottomView.layer.shadowRadius = 6;
    UIButton *addRelationGroupButton = [UIButton new];
    [bottomView addSubview:addRelationGroupButton];
    [addRelationGroupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.top.mas_equalTo(16);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(46);
    }];
    addRelationGroupButton.backgroundColor = FCBlueBackColor;
    [addRelationGroupButton setTitle:@"添加分组" forState:UIControlStateNormal];
    [addRelationGroupButton setTitleColor:FCWhiteColor forState:UIControlStateNormal];
    addRelationGroupButton.titleLabel.font = font15;
    addRelationGroupButton.layer.cornerRadius = 4;
    [addRelationGroupButton addTarget:self action:@selector(goAddRelationGroup) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView = [UITableView new];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(0);
        make.top.equalTo(topNoticeLabel.mas_bottom).mas_equalTo(0);
        make.bottom.equalTo(bottomView.mas_top).mas_equalTo(0);
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = FCBackColor;
    [self setExtraCellLineHidden:self.tableView];
    
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    [_tableView addGestureRecognizer:longTap];
    WJCWeakSelf
    topNoticeLabel.closeBlock = ^{
//        XMGLog(@"关闭");
        [weakSelf.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
            make.bottom.equalTo(bottomView.mas_top).mas_equalTo(0);
        }];
//        UIImageView *naviLineView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
//        naviLineView.backgroundColor = FCLineColor;
        UIView *naviLineView = [UIView new];
        [weakSelf.view addSubview:naviLineView];
        [naviLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
            make.height.mas_equalTo(0.5);
        }];
        naviLineView.backgroundColor = FCLineColor;
    };
}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    [tableView setTableFooterView:view];
}

#pragma mark - 前往添加分组
- (void)goAddRelationGroup{
    FCAddRelationGroupViewController *addRelationType = [[FCAddRelationGroupViewController alloc] init];
    [self.navigationController pushViewController:addRelationType animated:YES];
}

#pragma mark - 前往授权说明
- (void)goAuthorizationNote{
    XMGLog(@"授权说明");
    FCWebViewController *web=[FCWebViewController new];
    web.webString=[NSString stringWithFormat:@"%@/page/relational-grouping-authorization-statement",API_Render_Url];
    [self.navigationController pushViewController:web animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self getCacheData];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.showData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return IphonePlus ? 48 : 56;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FCRelationTypeDefaultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[FCRelationTypeDefaultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    }
    
    FCRelationTypeModel *relationType = self.showData[indexPath.row];
    
    [cell setDataWithRelationTypeName:relationType.name andEmplyeeName:relationType.manager.Name];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FCRelationTypeModel *relationType = self.showData[indexPath.row];
    FCAddRelationGroupViewController *addRelationTypeVC = [[FCAddRelationGroupViewController alloc] init];
    addRelationTypeVC.relationType = relationType;
    WJCWeakSelf;
    addRelationTypeVC.idBlock = ^(FCEmployeeModel *employee) {
        FCRelationTypeModel *relationType = weakSelf.showData[indexPath.row];
        relationType.manager.Name = employee.Name;
        [tableView reloadData];
    };
    
    [self.navigationController pushViewController:addRelationTypeVC animated:YES];
}

#pragma mark - Cell拖动排序
- (void)handlelongGesture:(UILongPressGestureRecognizer *)sender
{
    UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
    UIGestureRecognizerState state = longPress.state;
    
    CGPoint location = [sender locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
    
    static UIView *snapshot = nil;
    static NSIndexPath *sourceIndexPath = nil;
    
    switch (state) {
        case UIGestureRecognizerStateBegan: {
            if (indexPath) {
                sourceIndexPath = indexPath;
                UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                
                // Take a snapshot of the selected row using helper method.
                snapshot = [self customSnapshoFromView:cell];
                
                // Add the snapshot as subview, centered at cell's center...
                __block CGPoint center = cell.center;
                snapshot.center = center;
                snapshot.alpha = 0.0;
                [self.tableView addSubview:snapshot];
                [UIView animateWithDuration:0.25 animations:^{
                    // Offset for gesture location.
                    center.y = location.y;
                    snapshot.center = center;
                    snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
                    snapshot.alpha = 0.98;
                    
                    cell.alpha = 0.0f;
                    
                } completion:^(BOOL finished) {
                    cell.hidden = YES;
                }];
            }
            break;
        }
            
        case UIGestureRecognizerStateChanged: {
            CGPoint center = snapshot.center;
            center.y = location.y;
            snapshot.center = center;
            if (indexPath && ![indexPath isEqual:sourceIndexPath]) {
                [self.showData exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];
                // ... move the rows.
                [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];
//                [self.tableView moveSection:sourceIndexPath.section toSection:indexPath.section];
                // ... and update source so it is in sync with UI changes.
                sourceIndexPath = indexPath;
//
            }
            break;
        }
            
        default: {
            // Clean up.
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];
            [UIView animateWithDuration:0.25 animations:^{
                snapshot.center = cell.center;
                snapshot.transform = CGAffineTransformIdentity;
                snapshot.alpha = 0.0;
                cell.alpha = 1.0f;
            } completion:^(BOOL finished) {
                cell.hidden = NO;
                [snapshot removeFromSuperview];
                snapshot = nil;
            }];
            sourceIndexPath = nil;
            
            [self updateSort];
            break;
        }
    }
}

- (UIView *)customSnapshoFromView:(UIView *)inputView
{
    UIView *snapshot = nil;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 7.0) {
        //ios7.0 以下通过截图形式保存快照
        snapshot = [self customSnapShortFromViewEx:inputView];
    }else{
        //ios7.0 系统的快照方法
        snapshot = [inputView snapshotViewAfterScreenUpdates:YES];
    }
    
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    return snapshot;
}

- (UIView *)customSnapShortFromViewEx:(UIView *)inputView
{
    CGSize inSize = inputView.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(inSize, NO, [UIScreen mainScreen].scale);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView* snapshot = [[UIImageView alloc] initWithImage:image];
    
    return snapshot;
}

#pragma mark - 提交新排序
- (void)updateSort{
    NSMutableArray *arr=[NSMutableArray new];
    for (int i=0; i<self.showData.count; i++) {
        [arr addObject:self.showData[i].Id];
    }
    
    NSDictionary *args = @{
                           @"ids": arr
                           };
    [FCCustomerRelationRequest sortRelationTypeWithArgs:args success:^(id resultObj) {
        [SVProgressHUD dismiss];
//        XMGLog(@"===>%@", resultObj);
    } failure:^(NSError *error) {
//            XMGLog(@"===>%@", error);
    }];
}

#pragma mark - 获取数据
// 刷新数据
- (void)updateData{
    // 清除旧数据
    [self.newShowData removeAllObjects];
    // 加载新数据
    [self getRelationTypesData];
}

// 获取缓存数据
- (void)getCacheData{
    //获取缓存数据
    NSMutableDictionary *relationTypeParam = [NSMutableDictionary dictionary];
    relationTypeParam[@"isManage"] = @"YES";
    NSArray *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:relationTypeParam];
    NSMutableArray *cacheResult = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:cache];
    if (cacheResult.count) {
        self.showData = cacheResult;
        [self.tableView reloadData];
    }
    // 刷新新数据
    [self updateData];
    // 开启数据变化监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:CrmSupplyRelationChanged object:nil];
}

// 获取关系类型
- (void)getRelationTypesData{
    NSNumber *take = @(15);
    NSDictionary *args = @{@"isManage": @(YES),
                           @"enable": @(YES),
                           @"take": take,
                           @"skip": @(self.newShowData.count)
                           };
    WJCWeakSelf
    [FCCustomerRelationRequest getCrmSupplyRelationTypeWithArgs:args success:^(id resultObj) {
        FCRelationTypeListModel *relationTypesModel = [FCRelationTypeListModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationTypes"]];
        if (weakSelf.newShowData.count == 0) {
            [weakSelf.newShowData addObjectsFromArray:relationTypesModel.items];
        } else {
            // 去重
            BOOL isAdd = YES;
            for (FCRelationTypeModel *newModel in relationTypesModel.items) {
                for (FCRelationTypeModel *model in weakSelf.newShowData) {
                    if ([model.Id isEqualToString:newModel.Id]) {
                        isAdd = NO;
                        break;
                    }
                }
                if (isAdd) {
                    [weakSelf.newShowData addObject:newModel];
                }
            }
        }
//        [weakSelf.newShowData addObjectsFromArray:relationTypesModel.items];
        
        if (weakSelf.newShowData.count >= relationTypesModel.pageInfo.total) {
//            XMGLog(@"relationType 全部请求完成");
            weakSelf.showData = [NSMutableArray arrayWithArray:weakSelf.newShowData];
            [weakSelf.tableView reloadData];
            //缓存
            NSMutableDictionary *relationTypeParam = [NSMutableDictionary dictionary];
            relationTypeParam[@"isManage"] = @"YES";
            NSArray *cache = [FCRelationTypeModel mj_keyValuesArrayWithObjectArray:self.showData];
            [FCFuChengCacheTool saveHttpCache:cache urlString:FCCrmSupplyRelationTypesDataKey parameters:relationTypeParam];
        } else {
//            XMGLog(@"relationType 继续请求");
            [weakSelf getRelationTypesData];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
//        XMGLog(@"%@", error);
    }];
}

@end
